using System;
using System.Collections.Generic;
using System.Linq;
using Miyabi.Binary.Models;
using Miyabi.Common.Models;
using Miyabi.Contract.Models;
using Miyabi.ContractSdk;
using Miyabi.ModelSdk.Execution;

namespace Miyabi.Tests
{
    public class SC1 : ContractBase
    {
        static string s_tableName = "MyTable";

        public SC1(ContractInitializationContext ctx)
            : base(ctx)
        { }

        public override bool Instantiate(string[] args)
        {
            if (args.Length < 1)
            {
                return false;
            }

            var tableName = s_tableName + InstanceName;

            var tableDescriptor = new BinaryTableDescriptor(
                tableName,
                false,
                false,
                new[] { ContractAddress.FromInstanceId(InstanceId), });

            try
            {
                StateWriter.AddTable(tableDescriptor);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public override bool Delete()
        {
            var tableName = s_tableName + InstanceName;
            try
            {
                StateWriter.DeleteTable(tableName);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Write(ByteString key, ByteString val)
        {
            var tableName = s_tableName + InstanceName;
            var ctx = StateWriter;
            bool res = ctx.TryGetTableWriter(
                tableName, out IBinaryTableWriter table);
            if (!res)
            {
                throw new InvalidOperationException("missing table");
            }

            table.UpsertRow(key, val);
        }

        public ByteString Read(ByteString key)
        {
            var tableName = s_tableName + InstanceName;
            IStateReader reader = StateWriter;
            if (!reader.TryGetTableReader(
                tableName, out IBinaryTableReader table))
            {
                return null;
            }

            table.TryGetData(key, out var value);
            return value;
        }

        public override void UpdateInstanceOwners(
            IEnumerable<Address> toAdd,
            IEnumerable<Address> toRemove)
        {
            // Do nothing special
            // Can add some business logic here
            base.UpdateInstanceOwners(
                toAdd,
                toRemove);
        }
    }
}